import React,{Component} from 'react';
import HeaderBar from '../../components/headerNav/headBar';
import './enrollForm.css';
import { hashHistory } from 'react-router';
import enrollImg from '../../img/card/back.png'
import {port} from "../../public/index";
import cookie from 'react-cookie';
import {Msg} from 'react-weui'
import { timestampFormat } from '../../public'

export default class EnrollForm extends Component{
    constructor(props){
        super(props);
        this.state={
            id:this.props.location.query.id,
            title:this.props.location.query.title,
            subtitle:this.props.location.query.subtitle,
            minPic:this.props.location.query.minPic,
            sSkuModels:cookie.load('sSkuModels'),
            type:'subscribe',
            mustSelect:this.props.location.query.mustSelect,
            selectList:[]
        }
    }

    componentWillMount(){
        try{
            let token = window.getNativeAppToken();
            if(window.isNativeApp()){
                cookie.save('userId',token)
            }
        }catch (e){

        }

        try{
            let token = window.handler.getNativeAppToken();
            if(window.handler.isNativeApp()){
                cookie.save('userId',token)
            }
        }catch (e){

        }

        let data=window.sessionStorage.getItem("data");
        let selectList=window.sessionStorage.getItem("selectList");
        let sex=window.sessionStorage.getItem("sex");
        if(data){
            let json=JSON.parse(data);
            this.setState({
                name:json.name,//真实姓名
                sex:json.sex,//性别 0女1男
                birth:json.birth,
                phone:json.phone,
                address:json.address,
                remark:json.remark,
            })
            if(selectList){
                console.log('selectList is')
                console.log(selectList.split(','))
                this.setState({
                    selectList:selectList.split(",")
                })
            }
            if(sex){
                this.setState({
                    sex:sex
                })
            }
        }


            // this.refs.birth.state.inputValue=timestampFormat(data.birth,1)
    }

    isTrue(num){
        if(num==1){
            return true
        }else{
            return false
        }
    }

    forReturn(data,select){
        if(select||select==0){
            for(var key in data){
                if(key=='phone'){
                    var reg=/^1[3|4|5|8][0-9]\d{4,8}$/;
                    if(!reg.test(data[key])){
                        alert('手机号输入格式有误！请重新输入')
                        return false
                    }
                }
            }
            let mustSelect=this.state.mustSelect;
            if( Boolean(data.name)==this.isTrue(mustSelect.substr(0,1))&&Boolean(data.phone)==
                this.isTrue(mustSelect.substr(1,1))&&Boolean(data.birth)==
                this.isTrue(mustSelect.substr(2,1))&&Boolean(data.sex)==
                this.isTrue(mustSelect.substr(3,1))&&Boolean(data.address)==
                this.isTrue(mustSelect.substr(4,1))){
                return true
            }else{
                alert('您有信息没有填写完整！')
                return false
            }
        }else{
            alert('信息填写不完整,请填写完整！')
            return false;
        }
    }


    enrollSubmit(){

        let sex;
        var radio = document.getElementsByName("sex");
        for (var i=0; i<radio.length; i++) {
            if (radio[i].checked) {
                sex=radio[i].value
            }
        }



        let select;
        var radio = document.getElementsByName("select");
        for (var i=0; i<radio.length; i++) {
            if (radio[i].checked) {
                select=radio[i].value
            }
        }

        // card/subsOrder/create?token={token}
        let url =port + '/card/subsOrder/create?token='+cookie.load('userId');
        let data={
            sid:select?this.state.sSkuModels[select].sId:'',//产品id
            skuId:select?this.state.sSkuModels[select].id:'',
            price:select?this.state.sSkuModels[select].price:'',
            title:this.state.title?this.state.title:'',
            count:1,//购买份数，
            name:this.state.name?this.state.name:'',//真实姓名
            sex:sex?sex:'',//性别 0女1男
            birth:this.refs.birth?Date.parse(this.refs.birth.value)/1000:'',
            phone:this.state.phone?this.state.phone:'',
            address:this.state.address?this.state.address:'',
            remark:this.state.remark?this.state.remark:'',
            select:select
        }

        window.sessionStorage.setItem("data", JSON.stringify(data));
        window.sessionStorage.setItem("selectList", this.state.selectList);
        window.sessionStorage.setItem("sex", sex);




         this.forReturn(data,select)&&
         fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(res => {
            console.log(res.status)
            return res.json()
        })
            .then(json=>{
                if(json.code==201){
                    hashHistory.push({
                        pathname:'/myBankCard',
                        query:{
                            type: this.state.type,
                            orderId: json.data.id,
                        }
                    })
                }else{
                    alert(json.message)
                }
            })
            .catch(e =>{
                console.log(e)
            })
    }
    changeSelect(index){
        console.log('点击了')
        var list=this.state.selectList;
        console.log(list)
        for(var i=0;i<list.length;i++){
            list[i]=0;
        }
        list[index]=1;
        console.log(list)
        this.setState({
            selectList:list
        })
    }


    changeSex(sex){
        this.setState({
            sex:sex
        })
    }
    render(){
        return(
            <div>
                {/*{*/}
                    {/*!(this.props.location.query.token||this.state.isIOsApp) &&*/}
                    {/*<HeaderBar content="预约填写" type="3"/>*/}
                {/*}*/}
                <div className="enrollForm">
                    <div className="enrollFormImgBox">
                        <div>
                            <p>
                                <img src={this.state.minPic} alt=""/>
                            </p>
                        </div>
                        <div>
                            <h3>{this.state.title}</h3>
                            <h4>{this.state.subtitle}</h4>
                        </div>
                    </div>
                    <div>
                        <form className="enrollFormInfo">
                            {
                                this.state.mustSelect.substr(0, 1)==1&&
                                    <div>
                                        <label htmlFor="">
                                            <span>真实姓名</span>
                                            <input type="text" value={this.state.name}  onChange={
                                                (e)=>{
                                                    this.setState({
                                                        name:e.target.value
                                                    })
                                                }
                                            }/>
                                        </label>
                                    </div>
                            }

                            {
                                this.state.mustSelect.substr(1, 1)==1&&
                                <div>
                                    <label htmlFor="">
                                        <span>联系方式</span>
                                        <input type="number" value={this.state.phone}  onChange={
                                            (e)=>{
                                                this.setState({
                                                    phone:e.target.value
                                                })
                                            }
                                        }/>
                                    </label>
                                </div>
                            }


                            {
                                this.state.mustSelect.substr(2, 1)==1&&
                                <div>
                                    <label htmlFor="">
                                        <span>生日</span>
                                        <input type="Date" ref='birth' />
                                    </label>
                                </div>
                            }



                            {
                                this.state.mustSelect.substr(3, 1)==1&&
                                <div>
                                    <label htmlFor="">
                                        <span>性别</span>
                                        <div className="sexRadio">
                                            <div className="male">
                                                <input type="radio" name="sex" id="male" value="1" checked={this.state.sex==1?true:false}
                                                       onClick={this.changeSex.bind(this,1)}/>
                                                <label htmlFor="male">男</label>
                                            </div>
                                            <div className="famale">
                                                <input type="radio" name="sex" id="female" value="0" checked={this.state.sex==0?true:false}
                                                       onClick={this.changeSex.bind(this,0)}/>
                                                <label htmlFor="female">女</label>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            }


                            {
                                this.state.mustSelect.substr(4, 1)==1&&
                                <div>
                                    <label htmlFor="">
                                        <span>服务地址</span>
                                        <input type="text" value={this.state.address}  onChange={
                                            (e)=>{
                                                this.setState({
                                                    address:e.target.value
                                                })
                                            }
                                        }/>
                                    </label>
                                </div>
                            }


                            {
                                this.state.mustSelect.substr(5, 1)==1&&
                                <div>
                                    <label htmlFor="">
                                        <span>备注</span>
                                        <input type="text" value={this.state.remark}  onChange={
                                            (e)=>{
                                                this.setState({
                                                    remark:e.target.value
                                                })
                                            }
                                        }/>
                                    </label>
                                </div>
                            }


                                <div>
                                    <div className="plzselect">请选择</div>
                                    <ul className="radioSelect">
                                        {
                                            this.state.sSkuModels.map((data,index)=>{
                                                return(
                                                    <li htmlFor={'select'+index} key={index}>
                                                        <input type="radio" name="select" id={'select'+index} value={index}
                                                               checked={this.state.selectList[index]==1?true:false}
                                                                onClick={this.changeSelect.bind(this,index)}/>

                                                        <label htmlFor={'select'+index}>
                                                            <div>
                                                                <h2>{data.title}</h2>
                                                                {/*<h4>{data.subtitle?data.subtitle:''}</h4>*/}
                                                            </div>
                                                            <span>{data.price}</span>
                                                        </label>
                                                    </li>
                                                    
                                                )
                                            })
                                        }
                                    </ul>
                                </div>
                        </form>
                    </div>
                </div>
                <button  className="achievement" onClick={this.enrollSubmit.bind(this)}>
                    完成
                </button>
            </div>
        )
    }
}
